home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1453 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: HELP NEEDED: What the hell is wrong with my program?
  5. Date: Sun, 14 Jan 96 00:35:04 GMT
  6. Organization: none
  7. Message-ID: <821579704snz@genesis.demon.co.uk>
  8. References: <4d1qmp$h43@carbon.cudenver.edu>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <4d1qmp$h43@carbon.cudenver.edu>
  15.            exli@ouray.cudenver.edu "ELLIE XIAO-YU LI" writes:
  16.  
  17. >
  18. >first of all, i have to thank all of you who have answered me through email
  19. >or have followed up my post.  and here is more details about my problem.
  20. >
  21. >the system i am using is a dec osf/1.  the code is something like:
  22. >
  23. >#include <string.h>
  24. >
  25. >typedef struct {
  26. >        .
  27. >        .
  28. >        .
  29. >        char *name;
  30. >        .
  31. >        .
  32. >        .
  33. >} aStruct;
  34. >
  35. >aStruct *ptr;
  36. >char *str1="this is a test";
  37. >char *str2="this is another test";
  38. >
  39. >ptr=(aStruct *)malloc(sizeof(aStruct));
  40.  
  41. Did you include stdlib.h or otherwise declare malloc()? If not this statement
  42. results in undefined behaviour. Unfortunately you cast the result of malloc#
  43. to a pointer, it is better not to do this when writing in ANSI C since the
  44. compiler can then warn you there is a problem.
  45.  
  46. Always test the return value of malloc agaunst NULL for failure.
  47.  
  48. >ptr->name=(char *)malloc(strlen(str1));
  49.                           ^^^^^^^^^^^
  50.                           strlen(str1)+1
  51.  
  52. >strcpy(ptr->name, str1);                        /*no problem here*/
  53. >...
  54. >/*then later i want  ptr->name to point to another string*/
  55. >free(ptr->name);
  56. >ptr->name=(char *)malloc(strlen(str2));
  57.                           ^^^^^^^^^^^
  58.                           strlen(str2)+1
  59. >strcpy(ptr->name, str2);                        /*problem arised here*/
  60.  
  61. -- 
  62. -----------------------------------------
  63. Lawrence Kirby | fred@genesis.demon.co.uk
  64. Wilts, England | 70734.126@compuserve.com
  65. -----------------------------------------
  66.